package pw.hais.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.util.AttributeSet;
import android.widget.ImageView;

import pw.hais.helper.BitmapDrawableGCHelper;
import pw.hais.utils.L;

/**
 * Created by hais1992 on 2016/1/29/029.
 */
public class ImageGCView extends ImageView {
    public ImageGCView(Context context) {
        super(context);
    }

    public ImageGCView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ImageGCView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void setImageDrawable(Drawable drawable) {
        Drawable previousDrawable = getDrawable();
        super.setImageDrawable(drawable);

        //显示新的drawable
        notifyDrawable(drawable, true);

        //回收之前的图片
        notifyDrawable(previousDrawable, false);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        setImageDrawable(null);

//        if(removeListenter!=null){
//            removeListenter.remove();
//        }
//
//        if(bitmap!=null && !bitmap.isRecycled()){
//            bitmap.recycle();
//            bitmap = null;
//            System.gc();
//            L.i("----------------------------------ImageGCView-GC-");
//        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        try {
            super.onDraw(canvas);
        } catch (Exception e) {
            L.e("ImageGCView","onDraw() Canvas: trying to use a recycled bitmap");
        }
    }

    /**
     * 通知该drawable显示或者隐藏
     *
     * @param drawable
     * @param isDisplayed
     */
    public static void notifyDrawable(Drawable drawable, boolean isDisplayed) {
        if (drawable instanceof BitmapDrawableGCHelper) {
            ((BitmapDrawableGCHelper) drawable).setIsDisplayed(isDisplayed);
        } else if (drawable instanceof LayerDrawable) {
            LayerDrawable layerDrawable = (LayerDrawable) drawable;
            for (int i = 0, z = layerDrawable.getNumberOfLayers(); i < z; i++) {
                notifyDrawable(layerDrawable.getDrawable(i), isDisplayed);
            }
        }
    }



    private Bitmap bitmap;

    @Override
    public void setImageBitmap(Bitmap bm) {
        super.setImageBitmap(bm);
        bitmap = bm;
    }

    private RemoveListenter removeListenter;

    public void setRemoveListenter(RemoveListenter removeListenter) {
        this.removeListenter = removeListenter;
    }

    public interface RemoveListenter{
        void remove();
    }


}
